<?php
require 'functions.php';

$session = new \Models\MySession();

if (isset($_GET['book_id'])){
    $book = new Models\Books();   
    $queryResult = $book->getSelectedBook($_GET['book_id']);                      
    $data = [];
    foreach ($queryResult as $row) {
        $isCommentExists = (bool)$row['comment_id'];
        if ($isCommentExists){
                $data['comments'][$row['comment_id']]['content'] = $row['comment'];
                $data['comments'][$row['comment_id']]['date'] = $row['date'];
                $data['comments'][$row['comment_id']]['author'] = $row['user_name'];           
            }            
          $data['books'][$row['book_id']] = $row['book_title'];            
          $data['author_id'][$row['author_id']] = $row['author_id'];
          $data['author_name'][$row['author_name']] = $row['author_name'];
          @$data['author_name_and_id'] = array_combine($data['author_id'], $data['author_name']);            
          $data['book_id'] = $row['book_id']; 
          $book_idFromDB =$row['book_id']; 
        }                 
     if ($_SESSION) {
         $comment = new \Models\Comments();
         try {
            $comment->publishComment($_SESSION['userId'], $_SESSION['isLogged'], 
                 $_POST, @$_POST['comment'], $_GET['book_id']);             
         } catch (Exception $exc) {
             echo $exc->getMessage();
         }         
    }   
    if (!$_SESSION AND $_POST) {
      $data['errors_comment'][] = 'Only registrated user can write comment';
    }      
}

$data['userGreeting'] = '';
if($_SESSION and !empty($_SESSION['userId'] )){
    try {
        $userName = Models\User::getUserName($_SESSION['userId']); 
        $data['userGreeting'] = 'Hi <b>'.$userName.'</b>';   
    } catch (Exception $exc) {
        echo $exc->getMessage();
    }
}

@$data['isLogged'] = $_SESSION['isLogged'];
$data['errors']['nocomment'] = 'No comments for this boook. Be the first!';
$data['title'] = 'Book';
$data ['is_comment'] = $isCommentExists;
$data['content'] = './public_html/book_public.php';
$data['header'] = './inc/header.php';
render($data, $layout);





